﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;
using BusinessLogic;
using BusinessObject;
using Utility;
using System.Web.Security;
using System.Resources;
namespace WebTeamplate
{

    public partial class Admin_DMMatHang : BasePage
    {
        #region Fields
        public string urlDetail = "ChiTietMatHang.aspx";
        int count = 0;
        #endregion

        #region ViewState
        public int PageIndex
        {

            get
            {

                object o = ViewState["PageIndex"];

                if (o != null) return (int)o;

                return 0;

                //a default

            }

            set { ViewState["PageIndex"] = value; }

        }
        public string SortField
        {

            get
            {
                object o = ViewState["SortField"];
                if (o != null) return (string)o;
                return string.Empty;
            }

            set { ViewState["SortField"] = value; }

        }
        public string SortExpression
        {

            get
            {
                object o = ViewState["SortExpression"];
                if (o != null) return (string)o;
                return string.Empty;
            }

            set { ViewState["SortExpression"] = value; }

        }
        #endregion

        #region Init,Load
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientDefaultButton.SetPageDefaultButton(this.Page, btnSearch.ClientID);
            if (!Page.IsPostBack)
            {
                InitData();
                CommonFunction.LoadSubCate(drlLoaiMatHang, CommonFunction.DEFAULT_LOAIHANGHOA_CODE, false);
                ///////////
                CommonFunction.LoadSubCate(drlChungXe, CommonFunction.DEFAULT_CHUNGLOAIXE_CODE, true);
                LoadDMXe();
                //////////


                LoadData();
                drlLoaiMatHang.Focus();
            }
        }
        private void LoadDMXe()
        {
            List<DMXeResult> lstResult = DMXeUtil.GetByChungXe(ConvertValueObject.ParseInt(drlChungXe.SelectedValue));
            drlXe.Items.Clear();
            ListItem nullItem = new ListItem(BaseFunctions.COMBOBOX_NULL_VALUE, string.Empty);
            drlXe.Items.Add(nullItem);
            foreach (DMXeResult objXe in lstResult)
            {
                drlXe.Items.Add(new ListItem(objXe.TenXe, objXe.MaXe.ToString()));
            }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitTextControl();
            this.imgMaPhuTungSortDown.ImageUrl = imgTenMHSortDown.ImageUrl = imgMaMHSortDown.ImageUrl = CommonFunction.DEFAULT_SORTDOWN_IMAGEURL;
            this.imgMaPhuTungSortUp.ImageUrl = imgTenMHSortUp.ImageUrl = imgMaMHSortUp.ImageUrl = CommonFunction.DEFAULT_SORTUP_IMAGEURL;
            imgTenMHSortDown.Click += new ImageClickEventHandler(imgTenMHSortDown_Click);
            imgMaMHSortDown.Click += new ImageClickEventHandler(imgMaMHSortDown_Click);
            imgTenMHSortUp.Click += new ImageClickEventHandler(imgTenMHSortUp_Click);
            imgMaMHSortUp.Click += new ImageClickEventHandler(imgMaMHSortUp_Click);
            imgMaPhuTungSortUp.Click += new ImageClickEventHandler(imgMaPhuTungSortUp_Click);
            imgMaPhuTungSortDown.Click += new ImageClickEventHandler(imgMaPhuTungSortDown_Click);
        }


        #endregion

        #region Methods
        public void InitTextControl()
        {
            btnSearch.Text = Resources.Resource.LABEL_BUTTON_SEARCH;
            btnReset.Text = Resources.Resource.LABEL_BUTTON_RESET;
            btnAddNew.Text = Resources.Resource.LABEL_BUTTON_ADDNEW;
            btnDelete.Text = Resources.Resource.LABEL_DELETE;
            this.SortExpression = "ASC";
            this.SortField = "[TenMatHang]";
        }
        private void InitData()
        {
            this.PageIndex = 1;
            Pager1.PageSize = CommonFunction.DEFAULT_ADMIN_PAGE_SIZE;
            Pager2.PageSize = Pager1.PageSize;
            CommonFunction.InitStatusPublishForRadioButtonList(rblStatus);
        }
        public void LoadData()
        {
            hidListId.Value = string.Empty;
            hidListIdSelect.Value = string.Empty;
            MatHang objCate = new MatHang();
            objCate.ObjectSortOrder.SortExpression = this.SortExpression;
            objCate.ObjectSortOrder.SortField = this.SortField;
            objCate.ObjectPaging.PageIndex = this.PageIndex;
            objCate.ObjectPaging.PageSize = Pager1.PageSize;
            objCate.Condition = " where 1=1";
            if (drlLoaiMatHang.SelectedValue != string.Empty)
                objCate.Condition += " and MaLoaiHangHoa=" + drlLoaiMatHang.SelectedValue;
            if (txtMaMH.Text != string.Empty)
                objCate.Condition += " and MaMatHang like N'%" + txtMaMH.Text + "%' ";
            if (txtMaPhuTung.Text != string.Empty)
                objCate.Condition += " and MaPhuTung like N'%" + txtMaPhuTung.Text + "%' ";
            if (drlChungXe.SelectedValue!=string.Empty)
                objCate.Condition += " and cx.SubCategoryId=" + drlChungXe.SelectedValue.ToString();
            if (drlXe.SelectedValue != string.Empty)
                objCate.Condition += " and mh.MaXe=" + drlXe.SelectedValue.ToString();
            if (txtName.Text != string.Empty)
                objCate.Condition += " and tenMatHang like N'%" + txtName.Text + "%' ";
            if (rblStatus.SelectedValue != string.Empty)
                objCate.Condition += " and mh.[IsPublished]=" + rblStatus.SelectedValue + " ";
            List<MatHangResult> lstResult = MatHangUtil.SearchMatHangFormListMH(objCate);
            if (lstResult != null && lstResult.Count > 0)
                count = lstResult.Count;
            rptData.DataSource = lstResult;
            rptData.DataBind();
            Pager1.SetPaging(this.PageIndex, count, objCate.ToltalRow);
            Pager2.SetPaging(this.PageIndex, count, objCate.ToltalRow);
        }
        private void Delete(string id)
        {
            if (MatHangUtil.Delete(id))
                LoadData();

        }
        public void Publish(string id)
        {
            MatHang objMH = new MatHang();
            objMH.MaMatHang = id;
            if (MatHangUtil.Publish(objMH))
                LoadData();
        }
        #endregion

        #region Events,Handler
        protected void rptData_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                MatHangResult cate = (MatHangResult)e.Item.DataItem;
                if (cate == null)
                    return;
                Literal ltr = (Literal)e.Item.FindControl("ltrNo");
                ltr.Text = (e.Item.ItemIndex + 1).ToString();

                //ltr = (Literal)e.Item.FindControl("ltrSubCode");
                string url = urlDetail + "?id=" + cate.MaMatHang + "&act=" + CommonFunction.DEFAULT_COMMAND_EDIT;
                //ltr.Text = "<a href='" + url + "'>" + Server.HtmlEncode(cate.SubCategoryCode) + "</a>";
                ltr = (Literal)e.Item.FindControl("ltrMaMH");
                ltr.Text = "<a href='" + url + "'>" + Server.HtmlEncode(cate.MaMatHang) + "</a>";

                ltr = (Literal)e.Item.FindControl("ltrMaPhuTung");
                ltr.Text = "<a href='" + url + "'>" + Server.HtmlEncode(cate.MaPhuTung) + "</a>";


             

                // ltr = (Literal)e.Item.FindControl("ltrLoaiMH");
                //ltr.Text = Server.HtmlEncode(cate.TenLoaiMatHang.ToString());

                ImageButton imgButton = (ImageButton)e.Item.FindControl("btnPublish");
                imgButton.CommandArgument = cate.MaMatHang.ToString();
                if (cate.IsPublished)
                    imgButton.ImageUrl = CommonFunction.DEFAULT_ACTIVE_IMAGEURL;
                else
                    imgButton.ImageUrl = CommonFunction.DEFAULT_DEACTIVE_IMAGEURL;
                HyperLink hplEdit = (HyperLink)e.Item.FindControl("hplEdit");
                hplEdit.NavigateUrl = url;
                LinkButton lbtnDelete = (LinkButton)e.Item.FindControl("lbtnDelete");
                lbtnDelete.Text = Resources.Resource.LABEL_DELETE;
                lbtnDelete.CommandArgument = cate.MaMatHang.ToString();
                hidListId.Value += cate.MaMatHang + ";";
                System.Web.UI.HtmlControls.HtmlTableRow row=(System.Web.UI.HtmlControls.HtmlTableRow)e.Item.FindControl("rowData");
                //check so luong ton
                List<SubCategoryResult> lstKho = SubCategoryUtil.GetAllByCategory(CommonFunction.DEFAULT_WAREHOUSE_CODE);
                int tonkho = MatHangUtil.GetSoLuongTonByDonViTinh(cate.MaMatHang,int.MinValue, cate.DVT);
                ltr = (Literal)e.Item.FindControl("ltrTenMH");

                if (tonkho <=0)
                    ltr.Text = Server.HtmlEncode(cate.TenMatHang) + "&nbsp;<span class='emptyWarning'>(Hết hàng)</span>";
                else if (tonkho <= CommonFunction.WARNINGLEVEL1)
                    ltr.Text = Server.HtmlEncode(cate.TenMatHang) + "&nbsp;<img titlt='" + tonkho.ToString() + "' src='../App_Themes/Admin/images/warning1.gif' /><span class='emptyWarning'>(" + tonkho + ")</span>";
                else if (tonkho <= CommonFunction.WARNINGLEVEL2)
                    ltr.Text = Server.HtmlEncode(cate.TenMatHang) + "&nbsp;<img titlt='" + tonkho.ToString() + "' src='../App_Themes/Admin/images/warning2.gif' /><span class='emptyWarning'>(" + tonkho + ")</span>";
                else ltr.Text = Server.HtmlEncode(cate.TenMatHang);
                
            }
        }
        protected void rptData_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();
            switch (e.CommandName)
            {
                case "publish":
                    {
                        Publish(id);
                        break;
                    }
                case "delete":
                    {
                        List<HinhAnhMatHangResult> lstOldPic = HinhAnhMatHangUtil.GetAllByMatHang(id);
                        if (MatHangUtil.Delete(id))
                        {
                            DeleteMatHang(lstOldPic);
                            LoadData();
                        }
                        break;
                    }

            }

        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.SortExpression = "ASC";
            this.SortField = "[MaMatHang]";
            //reset sort order
            this.PageIndex = 1;
            LoadData();
        }
        void imgMaMHSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "MaMatHang";
            this.SortExpression = "DESC";
            LoadData();
        }
        void imgMaMHSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "MaMatHang";
            this.SortExpression = "ASC";
            LoadData();
        }
        void imgTenMHSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "TenMatHang";
            this.SortExpression = "ASC";
            LoadData();
        }
        void imgLoaiMHSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "SubCategoryName";
            this.SortExpression = "ASC";
            LoadData();
        }
        void imgTenMHSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "TenMatHang";
            this.SortExpression = "DESC";
            LoadData();
        }
        void imgLoaiMHSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "SubCategoryName";
            this.SortExpression = "DESC";
            LoadData();
        }
        void imgMaPhuTungSortDown_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "TenMatHang";
            this.SortExpression = CommonFunction.DEFAULT_SORTDOWN_EXPRESSION;
            LoadData();
        }

        void imgMaPhuTungSortUp_Click(object sender, ImageClickEventArgs e)
        {
            this.SortField = "TenMatHang";
            this.SortExpression = CommonFunction.DEFAULT_SORTUP_EXPRESSION;
            LoadData();
        }
        protected void Pager1_PageIndexChanging(object obj, PagerControl.PageIndexChangeEventArgs e)
        {
            this.PageIndex = e.newPageIndex;
            LoadData();
        }
        protected void Pager2_PageIndexChanging(object obj, PagerControl.PageIndexChangeEventArgs e)
        {
            this.PageIndex = e.newPageIndex;
            
            LoadData();
        }
        protected void Pager1_PageSizeChanging(object obj, PagerControl.PageSizeChangeEventArgs e)
        {
            this.PageIndex = 1;
            //  this.PageSize = e.newPageSize;
            Pager2.PageSize = e.newPageSize;
            LoadData();
        }
        protected void Pager2_PageSizeChanging(object obj, PagerControl.PageSizeChangeEventArgs e)
        {
            this.PageIndex = 1;
            Pager1.PageSize = e.newPageSize;
            //  this.PageSize = e.newPageSize;
            LoadData();
        }
        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Response.Redirect(urlDetail);
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {

            string[] arr = hidListIdSelect.Value.Split(';');
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i].ToString() != string.Empty)
                {
                    List<HinhAnhMatHangResult> lstOldPic = HinhAnhMatHangUtil.GetAllByMatHang(arr[i].ToString());
                    if (MatHangUtil.Delete(arr[i].ToString()))
                        DeleteMatHang(lstOldPic);

                }
            }

            LoadData();
        }
        protected void drlChungXe_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDMXe();
            LoadData();
        }
        private void DeleteImageProduct(string fileName)
        {
            if (fileName != string.Empty)
            {
                string fullPath = Server.MapPath(CommonFunction.DEFAULT_UPLOAD_PRODUCT);
                // string pathSmall = Server.MapPath(CommonFunction.DEFAULT_UPLOAD_PRODUCT_SMALL);
                string pathlarge = Server.MapPath(CommonFunction.DEFAULT_UPLOAD_PRODUCT_LARGE);
                fullPath += "\\" + fileName;
                // pathSmall += "\\" + fileName;
                pathlarge += "\\" + fileName;
                CommonFunction.DeleteFile(fullPath);
                //  CommonFunction.DeleteFile(pathSmall);
                CommonFunction.DeleteFile(pathlarge);
            }
        }
        public void DeleteMatHang(List<HinhAnhMatHangResult> lstOldPic)
        {
            string imageOld1 = string.Empty;
            string imageOld2 = string.Empty;           
            if (lstOldPic != null && lstOldPic.Count > 0)
            {
                imageOld1 = lstOldPic[0].ImageUrl;
                try
                {
                    imageOld2 = lstOldPic[1].ImageUrl;
                }
                catch
                {
                }
            }

            DeleteImageProduct(imageOld1);
            DeleteImageProduct(imageOld2);
        }
        #endregion

    }
}
